using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace ZSW.Framework.UIElement
{
    public class ZSWF_Imagebar : ZSWF_BaseUIElement
    {
        public Action<float> OnConfirm;
        public Action<float> OnValueChange;
        [SerializeField] private Text m_fillAmountText;
        [SerializeField] private Image m_imageBar;
        private Coroutine m_coroutine;
        public override void Init()
        {
            if (!m_imageBar)
            {
                m_imageBar = gameObject.GetComponent<Image>();
            }

            if (m_imageBar.type != Image.Type.Filled)
            {
                m_imageBar.type = Image.Type.Filled;
            }
            base.Init();
        }


        private void OnDisable()
        {
            if (m_coroutine != null)
            {
                StopCoroutine(m_coroutine);
            }
        }

        public void SetNA()
        {
            StopAllCoroutines();
            m_imageBar.fillAmount = 0;
            m_fillAmountText.text = "无";
        }

        public void SetValue(float value)
        {
            if (m_coroutine != null)
            {
                StopCoroutine(m_coroutine);
            }
            m_imageBar.fillAmount = value;

            m_fillAmountText.text = $"{Mathf.RoundToInt(value * 100)}%";
        }

        public void SliderValue(float value)
        {
            if (m_coroutine != null)
            {
                StopCoroutine(m_coroutine);
            }
            if (gameObject.activeInHierarchy)
            {
                m_coroutine = StartCoroutine(AnimateSlider(value));
            }
            else
            {
                SetValue(value);
            }
        }

        private IEnumerator AnimateSlider(float value)
        {
            float time = 0;
            float startValue = m_imageBar.fillAmount;
            float endValue = value;
            while (time < 1)
            {
                time += UnityEngine.Time.deltaTime;
                float tmpValue = Mathf.Lerp(startValue, endValue, time);
                m_imageBar.fillAmount = tmpValue;
                m_fillAmountText.text = $"{Mathf.RoundToInt(tmpValue * 100)}%";
                yield return null;
            }
        }

    }
}